package com.example.micro.netty.server.thread;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁demo -- 结果可以看出，读线程不会阻塞
 *
 * @author Code Farmer
 * @create 2020/10/14 2:19 上午
 */
public class ReadWriteLockDemo {

    private static Lock lock = new ReentrantLock();
    private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private static Lock readLock = readWriteLock.readLock();
    private static Lock writeLock = readWriteLock.writeLock();

    private String value;

    //模拟读操作
    public String handleRead(Lock lock) throws InterruptedException {
        lock.lock();
        try {
            Thread.sleep(2000);
            return value;
        } finally {
            lock.unlock();
        }
    }

    public void handleWrite(Lock lock, String index) throws InterruptedException {
        lock.lock();
        try {
            Thread.sleep(2000);
            value = index;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
        Runnable readRunable = () -> {
            try {
                String value = readWriteLockDemo.handleRead(readLock);
                System.out.println(value);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Runnable writeRunable = () -> {
            try {
                readWriteLockDemo.handleWrite(writeLock, new Random().toString());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        for (int i = 0; i < 18; i++) {
            new Thread(writeRunable).start();
        }

        for (int i = 0; i < 18; i++) {
            new Thread(readRunable).start();
        }
    }

}
